package com.cxm.helper.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxm.helper.annotation.LogApi;
import com.cxm.helper.exception.BusinessException;
import com.cxm.helper.pojo.User;
import com.cxm.helper.pojo.dto.UserLoginDTO;
import com.cxm.helper.pojo.dto.UserRegDTO;
import com.cxm.helper.pojo.dto.UserUpdateDTO;
import com.cxm.helper.pojo.vo.UserVO;
import com.cxm.helper.service.ConfigService;
import com.cxm.helper.service.UserService;
import com.cxm.helper.service.impl.AliyunOssService;
import com.cxm.helper.service.impl.AliyunSendSmsService;
import com.cxm.helper.util.Patterns;
import com.cxm.helper.util.RedisUtil;
import com.cxm.helper.util.ResponseEntity;
import com.cxm.helper.util.constant.AliyunOssConstant;
import com.cxm.helper.util.constant.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: chenximeng
 * @date: 2022/11/18 08:12
 */
@RestController
@Slf4j
@RequestMapping("/user/")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    AliyunOssService aliyunOssService;
    @Autowired
    ConfigService configService;
    @Autowired
    AliyunSendSmsService aliyunSendSmsService;
    @Autowired
    RedisUtil redisUtil;

    @PostMapping("login")
    @LogApi(level = LogApi.LogLevel.SECURE)
    public ResponseEntity<UserVO> login(@RequestBody UserLoginDTO user) {
        UserVO userVO = userService.login(user.getPhone(), user.getPassword(), false);
        StpUtil.login(userVO.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        userVO.setTokenName(tokenInfo.getTokenName());
        userVO.setTokenValue(tokenInfo.getTokenValue());
        return ResponseEntity.ok(userVO, "登陆成功");
    }

    @PostMapping("reg")
    @LogApi(level = LogApi.LogLevel.SECURE)
    public ResponseEntity reg(@RequestBody UserRegDTO user) {
        UserVO userVO = userService.reg(user);
        StpUtil.login(userVO.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        userVO.setTokenName(tokenInfo.getTokenName());
        userVO.setTokenValue(tokenInfo.getTokenValue());
        return ResponseEntity.ok(userVO, "注册成功");
    }

    @GetMapping("sendSmsCode/{phone}")
    public ResponseEntity getSmsCode(@PathVariable String phone) {
        User phoneUser = userService.getOne(new QueryWrapper<User>().eq("phone", phone));
        if (phoneUser != null) {
            throw new BusinessException("手机号已存在");
        }
        String redisKey = phone + RedisKeyConstant.PHONE_SMS_REG_SUFFIX;
        if (!Patterns.PHONE_NUMBER_PATTERN.matcher(phone).matches()) {
            throw new BusinessException("手机号不合法");
        }
        String code = redisUtil.get(redisKey);
        if(StrUtil.isNotBlank(code) && redisUtil.getExpire(phone) > 60) {
            throw new BusinessException("一分钟只能获取一次验证码");
        }
        String newCode = RandomUtil.randomNumbers(4);
        boolean flag;
        try{
            flag = aliyunSendSmsService.sendSmsCode(phone, newCode);
        }catch (Exception e) {
            log.error("send sms error,e:{}",e.toString());
            throw new BusinessException("验证码发送失败，请联系管理员");
        }
        if (!flag) {
            throw new BusinessException("验证码发送失败，请联系管理员");
        }
        redisUtil.set(redisKey, newCode, 5 * 60);
        return ResponseEntity.ok("发送验证码成功");
    }

    @PostMapping("/uploadAvatar")
    public ResponseEntity<String> uploadUserAvatar(MultipartFile file) {
        //返回图片在oss上的路径
        String url;
        try {
            url = aliyunOssService.uploadFileAvatar(file, AliyunOssConstant.USER_AVATAR_PATH);
        } catch (Exception e) {
            log.error("文件上传报错", e);
            throw new BusinessException("上传文件失败");
        }
        ResponseEntity<String> ok = ResponseEntity.ok();
        return ok.setData(url);
    }

    @PostMapping("/update")
    public ResponseEntity updateUser(@RequestBody UserUpdateDTO userUpdateDTO) {
        userService.update(userUpdateDTO);
        return ResponseEntity.ok();
    }

    @GetMapping("/verifyNickname")
    public ResponseEntity verifyNickName(String nickname) {
        if (StrUtil.isEmpty(nickname)) {
            return ResponseEntity.ok(false);
        }
        return ResponseEntity.ok(userService.verifyNickname(nickname));
    }

    @GetMapping("/verifyPhone")
    public ResponseEntity verifyPhone(String phone) {
        if (StrUtil.isEmpty(phone)) {
            return ResponseEntity.ok(false);
        }
        return ResponseEntity.ok(userService.verifyPhone(phone));
    }

    @GetMapping("/logout")
    public ResponseEntity logout() {
        StpUtil.logout(StpUtil.getLoginId());
        return ResponseEntity.ok();
    }

}
